using System;
using System.Collections;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using Sedna.Core.Controller;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Controls.Support;
using Sedna.Core.Controls.Support.Javascript;
using Sedna.Core.Controls.Support.Tab;

namespace Sedna.Core.Controls
{
	/// <summary>
	/// Control encapsulating processing and presentation of tab pages on the screen 
	/// </summary>
	 
	[ParseChildren(false)]
	[System.Web.UI.ControlBuilder(typeof(TabControlBuilder))]
	public class TabControl: BaseControl, INamingContainer, /*IPostBackEventHandler,*/ IClientScriptingControl
	{

        private Control tabContainer;
        private HtmlInputHidden hidden;
        private Table headerTable;
	    	    
        #region Properties

	    protected override HtmlTextWriterTag TagKey
	    {
            get { return HtmlTextWriterTag.Table; }
	    }

	    public override bool ClientScriptingEnabled
	    {
            get { return true; }
	        set {}
	    }

	    public ControlCollection Tabs
	    {
            get { return tabContainer.Controls; }   
	    }

		public int SelectedIndex
		{
			get
			{
                return Convert.ToInt32(hidden.Value, CultureInfo.InvariantCulture);
//			    foreach (Tab tab in Tabs)
//			    {
//			        if (tab.Selected)
//			        {
//                        return Tabs.IndexOf(tab);
//			        }
//			    }
//                SelectedIndex = 0;
//                return 0;
			}
			set
			{
                if (value < -1 || value >= Tabs.Count)
                {
                    throw new ArgumentException("Invalid SelectedIndex");
                }
			    hidden.Value = value.ToString(CultureInfo.InvariantCulture);
			    SyncSelectedIndex();

			}
        }


	    #endregion
	    
        public TabControl(IConfiguration configuration) : base(configuration)
		{
            tabContainer = new TabContainer();
            hidden = new HtmlInputHidden();
            headerTable = new Table();
            SelectedIndex = -1;
        }
	    
	    
//        public TabControl() : base(HtmlTextWriterTag.Table)
//		{
//			configurationId="configuration.default.TabControl";
//            tabContainer = new TabContainer();
//            hidden = new HtmlInputHidden();
//            headerTable = new Table();
//            SelectedIndex = -1;
//        }


//	    public void RaisePostBackEvent(string eventArgument)
//        {
//            SelectedIndex = Convert.ToInt32(eventArgument);
//        }

	    
	    
	    
		protected override void OnInit(EventArgs e)
		{
		    base.OnInit(e);
			EnsureChildControls();
		}
	    
//	    protected override void LoadViewState(object savedState)
//	    {
//	        base.LoadViewState(savedState);
//			object index=ViewState["selectedIndex"];
//			SelectedIndex = index!=null?(int)index:0;
//        }
//	    
//	    protected override object SaveViewState()
//	    {
//			ViewState["selectedIndex"]=SelectedIndex;
//	        return base.SaveViewState();
//	    }
//
	    protected override void OnLoad(EventArgs e)
	    {
	        if (!Page.IsPostBack)
	        {
                SelectedIndex = GetDefaultSelectedIndex();
	        } 
	        else
	        {
                SyncSelectedIndex();
	        }
	        base.OnLoad(e);
	    }

	    protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
	        base.AddAttributesToRender(writer);
			writer.AddAttribute(HtmlTextWriterAttribute.Width,"100%");
			writer.AddAttribute(HtmlTextWriterAttribute.Height, "100%");
			writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding,"0");
			writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
		}

//	    protected override void AddParsedSubObject(object obj)
//		{
//			if (obj is Tab)
//			{
//				Tabs.Add((Control)obj);		
//			}
//		}

		protected override void CreateChildControls()
		{
            Controls.Add(tabContainer);
		    Controls.Add(hidden);
		    Controls.Add(headerTable);
            headerTable.CellPadding = 0;
            headerTable.CellSpacing = 0;
			if (Tabs.Count==0)
			{
				Tab tab=new Tab();
				Tabs.Add(tab);
			}
		}

	    protected override void OnPreRender(EventArgs e)
	    {
	        base.OnPreRender(e);
	        ControlUtil.EnsureIdAttribute(this);
	        ControlUtil.EnsureIdAttribute(hidden);
	        ControlUtil.EnsureIdAttribute(headerTable);
	        if (ClientScriptingEnabled)
	        {
	            DeclareScriptVariable();
	        }
	        if (!Tabs[SelectedIndex].Visible)
	        {
	            foreach (Tab tab in Tabs)
	            {
                    if (!tab.Visible) continue;
                    SelectedIndex = Tabs.IndexOf(tab);
                    break;
	            }
	        }
	    }

	    protected override IDictionary BuildScriptParameters()
	    {
	        IDictionary parameters = base.BuildScriptParameters();
            parameters["hiddenId"] = hidden.ClientID;
            parameters["headerTableId"] = headerTable.ClientID;
            return parameters;
	    }

	    protected override void Render(HtmlTextWriter writer)
	    {
	        hidden.RenderControl(writer);
	        RenderBeginTag(writer);
	        writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
	        writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "15px");
	        writer.RenderBeginTag(HtmlTextWriterTag.Tr);
	        writer.RenderBeginTag(HtmlTextWriterTag.Td);
	        headerTable.RenderBeginTag(writer);
	        writer.RenderBeginTag(HtmlTextWriterTag.Tr);
//            int tabIndex = 0;
	        foreach  (Tab tab in Tabs)
	        {
	            if (!tab.Visible)
	            {
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
	                writer.RenderEndTag();
                    continue;
	            }
                writer.AddAttribute(HtmlTextWriterAttribute.Class, tab.Selected ? "smalltabselected" : "smalltab");
	            writer.RenderBeginTag(HtmlTextWriterTag.Td);
//	            writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, Tabs.IndexOf(tab).ToString()));
                writer.AddAttribute(HtmlTextWriterAttribute.Href, BuildLinkScript(Tabs.IndexOf(tab)));
	            writer.RenderBeginTag(HtmlTextWriterTag.A);
	            writer.Write(tab.Text);
	            writer.RenderEndTag();
	            writer.RenderEndTag();
//                tabIndex++;
	        }
	        writer.RenderEndTag();
	        headerTable.RenderEndTag(writer);
	        writer.RenderEndTag();
	        writer.RenderEndTag();
//	        Tabs[SelectedIndex].RenderControl(writer);
	        foreach (Tab tab in Tabs)
	        {
	            if (!tab.Visible)
	            {
	                writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
	                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
	                writer.RenderEndTag();
                    continue;
	            }
                tab.RenderControl(writer);
	        }
	        RenderEndTag(writer);
	    }

	    private string BuildLinkScript(int index)
	    {
            return
                String.Format("javascript: {0}.selectTab({1});", JavascriptUtil.ObjectReferenceByNode(NodeName), index);    
	    }
	    
	    private int GetDefaultSelectedIndex()
        {
            foreach (Tab tab in Tabs)
            {
                if (tab.Selected)
                {
                    return Tabs.IndexOf(tab);
                }
            }
            return 0;
        }

	    	    
		private void ClearSelection()
		{
            foreach (Tab tab in Tabs)
            {
                tab.Selected = false;
            }
		}

        private void SyncSelectedIndex()
        {
            ClearSelection();
            if (SelectedIndex > -1)
            {
                ((Tab)Tabs[SelectedIndex]).Selected = true;
            }
        }

	    protected override void Unbind()
	    {
	        base.Unbind();
            binder.Unbind("SelectedIndex");
            IExecutionContext executionContext = ExecutionContext.GetCurrent(ClientID);
            foreach (Tab tab in Tabs)
            {
                if (tab.VisibleUnbindPath == null)
                {
                    continue;
                }
                executionContext.SetPropertyValue(tab.VisibleUnbindPath, tab.Visible);
            }
        }

	    protected override void Bind()
	    {
	        base.Bind();
            binder.Bind("SelectedIndex");
	        IExecutionContext executionContext = ExecutionContext.GetCurrent(ClientID);
	        foreach (Tab tab in Tabs)
	        {
	            if (tab.VisibleBindPath==null)
	            {
                    continue;
	            }
                tab.Visible = (bool)executionContext.GetPropertyValue(tab.VisibleBindPath);
	        }
	    }
	}
}
